﻿Imports ComponentPro.Net.Mail
Imports ComponentPro.Net
Imports ComponentPro.Pdf
Imports System.IO
Imports PdfSharp.Xps
Imports System.IO.Packaging
Imports PdfSharp.Pdf
Imports PdfSharp.Xps.XpsModel
Imports ComponentPro.Pdf.Graphics
Imports Microsoft.LightSwitch.Details
Imports Microsoft.WindowsAzure.Storage
Imports Microsoft.WindowsAzure.Storage.Blob


Namespace LightSwitchApplication

    Public Class ApplicationDataService

        'TODO put in configuration file
        Const BlobConnStr = "DefaultEndpointsProtocol=https;AccountName=themuttscouts;AccountKey=4cywlBz6JG/CeGOYolsfogezG2xhqNOrShDPBFEQy9IHAaeve+Kza4QBVhco+nfm8fILED15ZoRb1eWnHAxjxA=="
        Const BlobContainerName = "mainphotos"
        Const BlobContainerURL = "https://themuttscouts.blob.core.windows.net/mainphotos/"

        Private Sub Animals_Updating(entity As Animal)
            'Save actual picture to blob storage only if it's changed
            'Dim prop As Microsoft.LightSwitch.Details.IEntityStorageProperty = entity.Details.Properties("Image")

            'If Not Object.Equals(prop.Value, prop.OriginalValue) Then
            'If prop.OriginalValue = Nothing Then
            'This guid becomes the name of the blob (image) in storage
            'Dim guid = Replace(entity.Name, " ", "") + "_" + System.Guid.NewGuid.ToString()
            'entity.ImageGuid = guid
            'We use this to display the image in our app.
            'entity.ImageUrl = BlobContainerURL + guid
            'End If
            'SaveAnimalImageToBlob(entity)
            'End If


            'If entity.Photo IsNot Nothing Then
            'Dim guid = Replace(entity.Name, " ", "") + "_" + System.Guid.NewGuid.ToString()
            'entity.ImageGuid = guid
            'entity.ImageUrl = BlobContainerURL + guid
            'SaveAnimalImageToBlob(entity)
            'End If


            'Dim mdate As Date = Nothing
            'Dim move As Movement = Nothing
            'Dim archived As Integer = Nothing
            'Dim movetype As MovementType = Nothing

            'If entity.Movements.Count <> 0 Then
            'For Each m In entity.Movements
            'If Not IsNothing(mdate) Then
            'If m.MovementDate >= mdate Then
            'If m.MovementDate = mdate Then
            'If m.Returned <> True Then
            'move = m
            'End If
            'Else
            'move = m
            'End If
            'End If
            'End If
            'mdate = m.MovementDate
            'Next
            'End If

            'If Not IsNothing(move) Then
            'If move.Returned <> True Or IsNothing(move.Returned) Then
            ''MsgBox("move.Returned = False")
            'Select Case move.MovementType.Id
            '    Case 1
            'archived = 1
            ''MsgBox("archived=True case 1")
            '    Case 2 'Foster
            'archived = 0
            '    Case 3 'Transfer
            'archived = 1
            '    Case 4 'Escaped
            'archived = 0
            '    Case 5 'Reclaimed
            'archived = 0
            '    Case 6 'Stolen
            'archived = 0
            '    Case 7 'Released to the Wild
            'archived = 0
            '    Case 8 'Retailer
            'archived = 0
            '    Case 9 'Reservation
            'archived = 0
            '    Case 10 'Canceled reservation
            'archived = 0
            '    Case 11 'Trial Adoption
            'archived = 1
            '    Case 12 'Permanent Foster
            'archived = 1
            '    Case Else
            'archived = 0
            'End Select
            'Else
            'archived = 0
            ''MsgBox("else archived = false")
            'End If

            'entity.ActiveMovementType = move.MovementType
            'entity.ActiveMovementID = move
            'entity.ActiveMovementDate = move.MovementDate
            'entity.ActiveMovementPerson = move.Person
            'entity.ActiveMovementLocation = move.Location
            'entity.ActiveMovementShelter = move.Shelter
            'entity.Archived = archived
            'End If
            'Dim newvals = "New Values:"
            'Dim oldvals = "Original Values:"
            '
            'For Each prop In entity.Details.Properties.All().
            'OfType(Of Microsoft.LightSwitch.Details.IEntityStorageProperty)()
            '
            'If prop.Name <> "Id" Then
            'If Not Object.Equals(prop.Value, prop.OriginalValue) Then
            'oldvals += String.Format("{0}{1}: {2}", vbCrLf, prop.Name, prop.OriginalValue)
            'newvals += String.Format("{0}{1}: {2}", vbCrLf, prop.Name, prop.Value)
            'End If
            'End If
            'Next

            'MsgBox(oldvals & " / " & newvals)
        End Sub

        Private Sub NotAdopted_PreprocessQuery(Archived As System.Nullable(Of Integer), ByRef query As System.Linq.IQueryable(Of LightSwitchApplication.Animal))
            If Archived = 1 Then 'Adopted
                query = From detail In query
                Where detail.Archived = 1
                'query = From a In query
                'Where(a.Movements.OrderByDescending(Function(b) b.MovementDate).FirstOrDefault).MovementType.Id = 1
                '        Select a
            ElseIf Archived Is Nothing Then 'All Adopted and Not Adopted
                query = From detail In query
                        Where 1 = 1
            ElseIf Archived = 2 Then 'All Adopted and Not Adopted
                query = From detail In query
                        Where 1 = 1
            ElseIf Archived = 0 Then 'Not Adopted
                query = From detail In query
                        Where detail.Archived = 0 Or detail.Archived Is Nothing
            Else 'All Adopted and Not Adopted
                query = From detail In query
                        Where 1 = 1
            End If

        End Sub

        Private Sub Animals_CanUpdate(ByRef result As Boolean)
            'result = Me.Application.User.HasPermission(Permissions.CanUpdateAnimals)
            result = Application.User.HasPermission(CanUpdateAnimals)
        End Sub

        Private Sub CanUpdateAnimal_CanExecute(ByRef result As Boolean)
            result = Me.Application.User.HasPermission(Permissions.CanUpdateAnimals)
        End Sub

        Private Sub CanUpdateAnimal_PreprocessQuery(ByRef query As System.Linq.IQueryable(Of LightSwitchApplication.Animal))
            query = From c In query Where 0 = 1
        End Sub

        Private Sub Movements_Inserting(entity As Movement)
            'MsgBox(entity.Animal.Movements.Count.ToString)
            Dim NowTime As DateTime = Now.ToUniversalTime()
            entity.NowTracker = NowTime
            Dim xM As Movement = Nothing

            If entity.Animal.Movements.Count > 0 Then
                For Each xMove As Movement In entity.Animal.Movements
                    If entity.MovementDate > xMove.MovementDate Then
                        xM = entity
                    Else
                        xM = xMove
                    End If
                Next

                Select Case xM.MovementType.Id
                    Case 1
                        entity.Animal.Archived = 1
                        'MsgBox("archived=True case 1")
                    Case 2 'Foster
                        entity.Animal.Archived = 0
                    Case 3 'Transfer
                        entity.Animal.Archived = 1
                    Case 4 'Escaped
                        entity.Animal.Archived = 1
                    Case 5 'Reclaimed
                        entity.Animal.Archived = 1
                    Case 6 'Stolen
                        entity.Animal.Archived = 1
                    Case 7 'Released to the Wild
                        entity.Animal.Archived = 1
                    Case 8 'Retailer
                        entity.Animal.Archived = 0
                    Case 9 'Reservation
                        entity.Animal.Archived = 0
                    Case 10 'Canceled reservation
                        entity.Animal.Archived = 0
                    Case 11 'Trial Adoption
                        entity.Animal.Archived = 1
                    Case 12 'Permanent Foster
                        entity.Animal.Archived = 1
                    Case 14 'Returned
                        entity.Animal.Archived = 0
                    Case Else
                        entity.Animal.Archived = 1
                End Select

                entity.Animal.ActiveMovementDate = xM.MovementDate
                entity.Animal.ActiveMovementID = xM
                entity.Animal.ActiveMovementLocation = xM.Location
                entity.Animal.ActiveMovementPerson = xM.Person
                entity.Animal.ActiveMovementShelter = xM.Shelter
                entity.Animal.ActiveMovementType = xM.MovementType
            Else
                Select Case entity.MovementType.Id
                    Case 1
                        entity.Animal.Archived = 1
                        'MsgBox("archived=True case 1")
                    Case 2 'Foster
                        entity.Animal.Archived = 0
                    Case 3 'Transfer
                        entity.Animal.Archived = 1
                    Case 4 'Escaped
                        entity.Animal.Archived = 1
                    Case 5 'Reclaimed
                        entity.Animal.Archived = 1
                    Case 6 'Stolen
                        entity.Animal.Archived = 1
                    Case 7 'Released to the Wild
                        entity.Animal.Archived = 1
                    Case 8 'Retailer
                        entity.Animal.Archived = 0
                    Case 9 'Reservation
                        entity.Animal.Archived = 0
                    Case 10 'Canceled reservation
                        entity.Animal.Archived = 0
                    Case 11 'Trial Adoption
                        entity.Animal.Archived = 1
                    Case 12 'Permanent Foster
                        entity.Animal.Archived = 1
                    Case 14 'Returned
                        entity.Animal.Archived = 0
                    Case Else
                        entity.Animal.Archived = 1
                End Select

                entity.Animal.ActiveMovementDate = entity.MovementDate
                entity.Animal.ActiveMovementID = entity
                entity.Animal.ActiveMovementLocation = entity.Location
                entity.Animal.ActiveMovementPerson = entity.Person
                entity.Animal.ActiveMovementShelter = entity.Shelter
                entity.Animal.ActiveMovementType = entity.MovementType

                'MsgBox("test")
                'Dim xTime As DateTracking = entity.Animal.DateTrackings.Where(Function(a) a.EndDate Is Nothing).FirstOrDefault
                'MsgBox(xTime.Animal.Name)
                'If Not IsNothing(xTime) Then
                'MsgBox("Test")
                'xTime.EndDate = entity.MovementDate.Date
                'xTime.Movement = entity
                'xTime.Location = "Boarding"
                'End If
            End If

            Dim xTime As DateTracking = entity.Animal.DateTrackings.Where(Function(a) a.EndDate Is Nothing).FirstOrDefault
            If Not IsNothing(xTime) Then
                'MsgBox("Test")
                xTime.EndDate = entity.MovementDate.Date
                xTime.EndTracking = NowTime

                Dim newTime As New DateTracking
                newTime.Animal = entity.Animal
                newTime.StartDate = entity.MovementDate
                newTime.StartTracking = NowTime
                If entity.MovementType.Id = 1 Then
                    newTime.Location = "Adopted"
                ElseIf entity.MovementType.Id = 2 Then
                    newTime.Location = "Foster"
                ElseIf entity.MovementType.Id = 11 Then
                    newTime.Location = "Trial Adoption"
                ElseIf entity.MovementType.Id = 12 Then
                    newTime.Location = "Permanent Foster"
                ElseIf entity.MovementType.Id = 14 Then
                    newTime.Location = "Boarding"
                Else
                    newTime.Location = "Other"
                End If

                'xTime.Location = "Boarding"
            End If

        End Sub

        Private Sub Movements_Updating(entity As Movement)
            Dim xM As Movement = Nothing

            If entity.Animal.Movements.Count > 0 Then
                For Each xMove As Movement In entity.Animal.Movements
                    If entity.MovementDate > xMove.MovementDate Then
                        xM = entity
                    Else
                        xM = xMove
                    End If
                Next

                Select Case xM.MovementType.Id
                    Case 1
                        entity.Animal.Archived = 1
                        'MsgBox("archived=True case 1")
                    Case 2 'Foster
                        entity.Animal.Archived = 0
                    Case 3 'Transfer
                        entity.Animal.Archived = 1
                    Case 4 'Escaped
                        entity.Animal.Archived = 1
                    Case 5 'Reclaimed
                        entity.Animal.Archived = 1
                    Case 6 'Stolen
                        entity.Animal.Archived = 1
                    Case 7 'Released to the Wild
                        entity.Animal.Archived = 1
                    Case 8 'Retailer
                        entity.Animal.Archived = 0
                    Case 9 'Reservation
                        entity.Animal.Archived = 0
                    Case 10 'Canceled reservation
                        entity.Animal.Archived = 0
                    Case 11 'Trial Adoption
                        entity.Animal.Archived = 1
                    Case 12 'Permanent Foster
                        entity.Animal.Archived = 1
                    Case 14 'Returned
                        entity.Animal.Archived = 0
                    Case Else
                        entity.Animal.Archived = 1
                End Select

                entity.Animal.ActiveMovementDate = xM.MovementDate
                entity.Animal.ActiveMovementID = xM
                entity.Animal.ActiveMovementLocation = xM.Location
                entity.Animal.ActiveMovementPerson = xM.Person
                entity.Animal.ActiveMovementShelter = xM.Shelter
                entity.Animal.ActiveMovementType = xM.MovementType
            Else
                Select Case entity.MovementType.Id
                    Case 1
                        entity.Animal.Archived = 1
                        'MsgBox("archived=True case 1")
                    Case 2 'Foster
                        entity.Animal.Archived = 0
                    Case 3 'Transfer
                        entity.Animal.Archived = 1
                    Case 4 'Escaped
                        entity.Animal.Archived = 1
                    Case 5 'Reclaimed
                        entity.Animal.Archived = 1
                    Case 6 'Stolen
                        entity.Animal.Archived = 1
                    Case 7 'Released to the Wild
                        entity.Animal.Archived = 1
                    Case 8 'Retailer
                        entity.Animal.Archived = 0
                    Case 9 'Reservation
                        entity.Animal.Archived = 0
                    Case 10 'Canceled reservation
                        entity.Animal.Archived = 0
                    Case 11 'Trial Adoption
                        entity.Animal.Archived = 1
                    Case 12 'Permanent Foster
                        entity.Animal.Archived = 1
                    Case 14 'Returned
                        entity.Animal.Archived = 0
                    Case Else
                        entity.Animal.Archived = 1
                End Select

                entity.Animal.ActiveMovementDate = entity.MovementDate
                entity.Animal.ActiveMovementID = entity
                entity.Animal.ActiveMovementLocation = entity.Location
                entity.Animal.ActiveMovementPerson = entity.Person
                entity.Animal.ActiveMovementShelter = entity.Shelter
                entity.Animal.ActiveMovementType = entity.MovementType
            End If
        End Sub

        Private Sub Animals_Inserted(entity As Animal)
            '' Create a new instance of the Smtp class. 
            'Dim client As New Smtp()

            '' Connect to the server. 
            ''client.Connect("smtp.gmail.com")
            'ComponentPro.Security.SecuritySettings.MediumTrust = True
            '' Or you can specify the SMTP port with 
            'client.Connect("smtp.gmail.com", 465, SecurityMode.Implicit)

            '' Login to the server. 
            'client.Authenticate("onlyouknowho@gmail.com", "mey291375")

            '' ... 

            '' Create a new mail message. 
            'Dim msg As New MailMessage()
            'msg.Subject = "Test Subject"
            'msg.BodyText = entity.Name
            'msg.From = "onlyouknowho@gmail.com"
            'msg.To = "frank.h.meyers@gmail.com"

            '' Send the message. 
            'client.Send(msg)

            ' ... 

            'Console.WriteLine("Message sent successfully.")

            '' Disconnect. 
            'client.Disconnect()
        End Sub

        Private Sub Emails_Inserting(entity As Email)
            Dim toAddresses As IEnumerable(Of String) = entity.ToEmailAddresses.Split(New Char() {","c})
            Dim ccAddresses As IEnumerable(Of String) = Nothing
            Dim bccAddresses As IEnumerable(Of String) = Nothing
            Dim subject As String = ""
            Dim fromaddress As String = "themuttscouts@gmail.com"
            Dim message As String = ""
            Dim ishtml As Boolean = False
            Dim includemedia As Boolean = False
            Dim ea As New EmailAdapter()
            Dim pdfbyte() As Byte = Nothing
            Try
                If entity.CcEmailAddresses IsNot Nothing Then
                    ccAddresses = entity.CcEmailAddresses.Split(New Char() {","c})
                End If
                If entity.BccEmailAddresses IsNot Nothing Then
                    bccAddresses = entity.BccEmailAddresses.Split(New Char() {","c})
                End If
                If entity.Subject IsNot Nothing Then
                    subject = entity.Subject
                End If
                If entity.FromEmailAddress IsNot Nothing Then
                    fromaddress = entity.FromEmailAddress
                End If
                If entity.Message IsNot Nothing Then
                    message = entity.Message
                End If
                If entity.IsHTML = True Then
                    ishtml = entity.IsHTML
                End If
                If entity.IncludeMedia = True Then
                    includemedia = entity.IncludeMedia
                End If
                If entity.IncludeMedia Then
                    If entity.Animal.MediaCollection.Count > 0 Then
                        Dim newPDF As New ComponentPro.Pdf.PdfDocument()
                        Dim pdfStream As New MemoryStream()
                        Dim xpsStream As New MemoryStream()
                        Try
                            For Each xfile In entity.Animal.MediaCollection
                                newPDF.CompressionLevel = PdfCompressionLevel.Best
                                If xfile.FileName.EndsWith(".pdf") Then
                                    PdfDocumentBase.Merge(newPDF, xfile.File)
                                ElseIf xfile.FileName.EndsWith(".xps") Then
                                    Dim xpsStream2 As New MemoryStream(xfile.File)
                                    Dim xpsbyte() As Byte = Nothing
                                    Try
                                        PdfSharp.Xps.XpsConverter.Convert(XpsDocument.Open(xpsStream2), xpsStream, 0)
                                        xpsbyte = xpsStream.ToArray()
                                        PdfDocumentBase.Merge(newPDF, xpsbyte)
                                    Catch ex As Exception
                                        Dim xerr = Me.DataWorkspace.ApplicationData.ErrorsSet.AddNew
                                        xerr.ErrorDescription = ex.Message
                                    Finally
                                        xpsbyte = Nothing
                                        xpsStream2.Dispose()
                                    End Try
                                Else
                                    Dim imagestream As New MemoryStream(xfile.File)
                                    Dim section As PdfSection = newPDF.Sections.Add()
                                    Dim page As ComponentPro.Pdf.PdfPage = Nothing
                                    Dim g As PdfGraphics = Nothing
                                    Dim ximage As New PdfBitmap(imagestream)
                                    Try
                                        page = section.Pages.Add()
                                        section.PageSettings.Margins.All = 10
                                        g = page.Graphics
                                        ximage.ActiveFrame = 0
                                        g.DrawImage(ximage, 0, 0, page.GetClientSize().Width, page.GetClientSize().Height)
                                    Catch ex As Exception
                                        Dim xerr = Me.DataWorkspace.ApplicationData.ErrorsSet.AddNew
                                        xerr.ErrorDescription = ex.Message
                                    Finally
                                        ximage.Dispose()
                                        imagestream.Dispose()
                                        section = Nothing
                                        page = Nothing
                                        g = Nothing
                                    End Try
                                End If
                            Next
                            newPDF.Save(pdfStream)
                            pdfbyte = pdfStream.ToArray()
                        Catch ex As Exception
                            Dim xerr = Me.DataWorkspace.ApplicationData.ErrorsSet.AddNew
                            xerr.ErrorDescription = ex.Message
                            xerr.ErrorName = "1"
                        Finally
                            newPDF.Close()
                            pdfStream.Dispose()
                            xpsStream.Dispose()
                        End Try
                    End If
                End If
                ea.SendEmail(toAddresses, fromaddress, subject, message, pdfbyte, includemedia, ccAddresses, bccAddresses, False)
            Catch ex As Exception
                Dim xerr = Me.DataWorkspace.ApplicationData.ErrorsSet.AddNew
                xerr.ErrorDescription = ex.Source
                xerr.ErrorName = "2"
            Finally
                toAddresses = Nothing
                ccAddresses = Nothing
                bccAddresses = Nothing
                subject = Nothing
                fromaddress = Nothing
                message = Nothing
                ishtml = False
                includemedia = False
                pdfbyte = Nothing
            End Try

            'Me.Details.DiscardChanges()
        End Sub

        Private Sub Animals_CanDelete(ByRef result As Boolean)
            result = Me.Application.User.HasPermission(Permissions.SecurityAdministration)
        End Sub

        Private Sub Animals_CanInsert(ByRef result As Boolean)
            result = Me.Application.User.HasPermission(Permissions.CanUpdateAnimals)
        End Sub

        Private Sub Animals_CanRead(ByRef result As Boolean)
            result = Me.Application.User.HasPermission(Permissions.CanViewAnimals)
        End Sub

        Private Sub Emails_CanRead(ByRef result As Boolean)
            result = Me.Application.User.HasPermission(Permissions.CanEmail)
        End Sub

        Private Sub Persons_CanUpdate(ByRef result As Boolean)
            result = Me.Application.User.HasPermission(Permissions.CanUpdatePeople)
        End Sub

        Private Sub MediaSet_CanInsert(ByRef result As Boolean)
            result = Me.Application.User.HasPermission(Permissions.CanUpdateMedia)
        End Sub

        Private Sub MediaSet_CanUpdate(ByRef result As Boolean)
            result = Me.Application.User.HasPermission(Permissions.CanUpdateMedia)
        End Sub

        Private Sub MediaSet_CanDelete(ByRef result As Boolean)
            result = Me.Application.User.HasPermission(Permissions.CanUpdateMedia)
        End Sub

        Private Sub Persons_CanDelete(ByRef result As Boolean)
            result = Me.Application.User.HasPermission(Permissions.SecurityAdministration)
        End Sub

        Private Sub Persons_CanInsert(ByRef result As Boolean)
            result = Me.Application.User.HasPermission(Permissions.CanUpdatePeople)
        End Sub

        Private Sub Persons_CanRead(ByRef result As Boolean)
            result = Me.Application.User.HasPermission(Permissions.CanViewPeople)
        End Sub

        Private Sub Logs_CanDelete(ByRef result As Boolean)
            result = Me.Application.User.HasPermission(Permissions.CanUpdateAnimals)
        End Sub

        Private Sub Logs_CanInsert(ByRef result As Boolean)
            result = Me.Application.User.HasPermission(Permissions.CanCreateLogs)
        End Sub

        Private Sub Logs_CanRead(ByRef result As Boolean)
            result = Me.Application.User.HasPermission(Permissions.CanViewAnimals)
        End Sub

        Private Sub Logs_CanUpdate(ByRef result As Boolean)
            result = Me.Application.User.HasPermission(Permissions.CanUpdateAnimals)
        End Sub

        Private Sub MediaSet_CanRead(ByRef result As Boolean)
            result = Me.Application.User.HasPermission(Permissions.CanViewAnimals)
        End Sub

        Private Sub Movements_CanDelete(ByRef result As Boolean)
            result = Me.Application.User.HasPermission(Permissions.CanUpdateMovements)
        End Sub

        Private Sub Movements_CanInsert(ByRef result As Boolean)
            result = Me.Application.User.HasPermission(Permissions.CanUpdateMovements)
        End Sub

        Private Sub Movements_CanRead(ByRef result As Boolean)
            result = Me.Application.User.HasPermission(Permissions.CanViewAnimals)
        End Sub

        Private Sub Movements_CanUpdate(ByRef result As Boolean)
            result = Me.Application.User.HasPermission(Permissions.CanUpdateMovements)
        End Sub

        Private Sub Vaccines_CanDelete(ByRef result As Boolean)
            result = Me.Application.User.HasPermission(Permissions.CanUpdateVaccines)
        End Sub

        Private Sub Vaccines_CanInsert(ByRef result As Boolean)
            result = Me.Application.User.HasPermission(Permissions.CanUpdateVaccines)
        End Sub

        Private Sub Vaccines_CanRead(ByRef result As Boolean)
            result = Me.Application.User.HasPermission(Permissions.CanViewAnimals)
        End Sub

        Private Sub Vaccines_CanUpdate(ByRef result As Boolean)
            result = Me.Application.User.HasPermission(Permissions.CanUpdateVaccines)
        End Sub

        Private Sub CanUpdatePerson_CanExecute(ByRef result As Boolean)
            result = Me.Application.User.HasPermission(Permissions.CanUpdatePeople)
        End Sub

        Private Sub CanUpdatePerson_PreprocessQuery(ByRef query As IQueryable(Of Person))
            query = From c In query Where 0 = 1
        End Sub

        Private Sub PersonFlagMultis_CanDelete(ByRef result As Boolean)
            result = Me.Application.User.HasPermission(Permissions.CanUpdatePeople)
        End Sub

        Private Sub PersonFlagMultis_CanInsert(ByRef result As Boolean)
            result = Me.Application.User.HasPermission(Permissions.CanUpdatePeople)
        End Sub

        Private Sub PersonFlagMultis_CanRead(ByRef result As Boolean)
            result = Me.Application.User.HasPermission(Permissions.CanViewPeople)
        End Sub

        Private Sub PersonFlagMultis_CanUpdate(ByRef result As Boolean)
            result = Me.Application.User.HasPermission(Permissions.CanUpdatePeople)
        End Sub

        Private Sub MonthlyBoarding_PreprocessQuery(AnimalMonth As System.Nullable(Of Integer), AnimalYear As System.Nullable(Of Integer), ByRef query As System.Linq.IQueryable(Of LightSwitchApplication.Animal))
            'query = query.Where(Function(a) Microsoft.VisualBasic.DateAndTime.Month(a.DateBroughtIn) <= AnimalMonth).Where(Function(b) Microsoft.VisualBasic.DateAndTime.Year(b.DateBroughtIn) <= AnimalYear).Where(Function(c) c.Movements.Where(Function(d) d.MovementType.Title = "Adopted").Select(c.Movements.)
        End Sub

        Private Sub Animals_Inserting(entity As Animal)
            If IsNothing(entity.DateBroughtIn) Then
                entity.DateBroughtIn = Today
            End If
            entity.Archived = 0

            Dim xTime As New DateTracking
            xTime.Animal = entity
            xTime.StartDate = entity.DateBroughtIn
            xTime.Location = "Boarding"

            'This guid becomes the name of the blob (image) in storage
            'Dim guid = Replace(entity.Name, " ", "") + "_" + System.Guid.NewGuid.ToString()
            'entity.ImageGuid = guid
            ''We use this to display the image in our app.
            'entity.ImageUrl = BlobContainerURL + guid
            '
            ''Save actual picture to blob storage 
            'SaveAnimalImageToBlob(entity)
        End Sub

        Private Sub SaveChanges_Executing()
            Try

            Catch ex As Exception
                Dim xerr = Me.DataWorkspace.ApplicationData.ErrorsSet.AddNew
                xerr.ErrorDescription = ex.Message
            End Try
        End Sub

        Private Sub Pictures_Inserting(entity As Picture)
            ''This guid becomes the name of the blob (image) in storage
            'Dim guid = entity.Animal.Name + "_" + System.Guid.NewGuid.ToString()
            'entity.ImageGuid = guid
            ''We use this to display the image in our app.
            'entity.ImageUrl = BlobContainerURL + guid

            ''Save actual picture to blob storage 
            'SaveImageToBlob(entity)
        End Sub

        Private Sub Pictures_Updating(entity As Picture)
            'Save actual picture to blob storage only if it's changed
            Dim prop As Microsoft.LightSwitch.Details.IEntityStorageProperty =
                entity.Details.Properties("Image")

            If Not Object.Equals(prop.Value, prop.OriginalValue) Then
                SaveImageToBlob(entity)
            End If
        End Sub

        Private Sub SaveImageToBlob(p As Picture)
            Dim blobContainer = GetBlobContainer()

            'Get reference to the picture blob or create if not exists. 
            Dim blockBlob As CloudBlockBlob = blobContainer.GetBlockBlobReference(p.ImageGuid)

            'Save to storage
            blockBlob.UploadFromByteArray(p.Image, 0, p.Image.Length)

            'Now that it's saved to storage, set the Image database property null
            p.Image = Nothing
        End Sub

        Private Sub SaveAnimalImageToBlob(p As Animal)
            Dim blobContainer = GetBlobContainer()

            'Get reference to the picture blob or create if not exists.
            Dim blockBlob As CloudBlockBlob = blobContainer.GetBlockBlobReference(p.ImageGuid)

            If p.Image Is Nothing Then
                If p.Photo IsNot Nothing Then
                    blockBlob.UploadFromByteArray(p.Photo, 0, p.Photo.Length)
                End If
            Else
                blockBlob.UploadFromByteArray(p.Image, 0, p.Image.Length)
            End If
            'Save to storage
            'blockBlob.UploadFromByteArray(p.Image, 0, p.Image.Length)

            'Now that it's saved to storage, set the Image database property null
            p.Image = Nothing
        End Sub

        Private Sub DeleteImageFromBlob(p As Picture)
            Dim blobContainer = GetBlobContainer()

            'Get reference to the picture blob or create if not exists. 
            Dim blockBlob As CloudBlockBlob = blobContainer.GetBlockBlobReference(p.ImageGuid)

            'Save to storage
            'blockBlob.UploadFromByteArray(p.Image, 0, p.Image.Length)
            blockBlob.DeleteIfExists(DeleteSnapshotsOption.IncludeSnapshots)

            'Now that it's saved to storage, set the Image database property null
            p.Image = Nothing
        End Sub

        Private Sub DeleteAnimalImageFromBlob(p As Animal)
            Dim blobContainer = GetBlobContainer()

            'Get reference to the picture blob or create if not exists. 
            Dim blockBlob As CloudBlockBlob = blobContainer.GetBlockBlobReference(p.ImageGuid)

            'Save to storage
            'blockBlob.UploadFromByteArray(p.Image, 0, p.Image.Length)
            blockBlob.DeleteIfExists(DeleteSnapshotsOption.IncludeSnapshots)

            'Now that it's saved to storage, set the Image database property null
            p.Image = Nothing
        End Sub

        Private Function GetBlobContainer() As CloudBlobContainer
            'Get our blob storage account
            Dim storageAccount As CloudStorageAccount = CloudStorageAccount.Parse(BlobConnStr)
            'Create the blob client
            Dim blobClient As CloudBlobClient = storageAccount.CreateCloudBlobClient()
            'Retrieve reference to a previously created container.
            Return blobClient.GetContainerReference(BlobContainerName)

        End Function

        Private Sub Query_Executed(queryDescriptor As QueryExecutedDescriptor)
            'This would be necessary if using the Silverlight client.
            'If queryDescriptor.SourceElementType.Name = "Picture" Then

            'For Each p As Picture In queryDescriptor.Results
            'ReadImageFromBlob(p)
            'Next
            'End If

            If queryDescriptor.SourceElementType.Name = "Animal" Then
                'Dim blobContainer = GetBlobContainer()

                For Each a As Animal In queryDescriptor.Results

                    'If a.ImageGuid = Nothing Then
                    'Dim guid = a.Name + "_" + System.Guid.NewGuid.ToString()
                    'a.ImageGuid = guid
                    ''We use this to display the image in our app.
                    'a.ImageUrl = BlobContainerURL + guid
                    'SaveChanges()

                    ''Get reference to the picture blob or create if not exists.
                    ''Dim blockBlob As CloudBlockBlob = blobContainer.GetBlockBlobReference(a.ImageGuid)
                    'Dim blockBlob As CloudBlockBlob = blobContainer.GetBlockBlobReference(guid)

                    'If a.Photo IsNot Nothing Then
                    'blockBlob.UploadFromByteArray(a.Photo, 0, a.Photo.Length)
                    'End If
                    'End If
                    'If a.ImageGuid <> Nothing Then
                    'If Left(a.Name, 1) = "A" Then
                    'ReadAnimalImageFromBlob(a)
                    'End If
                    'End If

                    'ReadAnimalImageFromBlob(a)
                    'DeleteAnimalImageFromBlob(a)
                    'a.ImageUrl = Nothing
                    'a.ImageGuid = Nothing
                    'SaveChanges()
                Next
            End If
        End Sub

        Private Sub ReadImageFromBlob(p As Picture)
            'Retrieve reference to the picture blob named after it's Guid.
            If p.ImageGuid IsNot Nothing Then
                Dim blobContainer = GetBlobContainer()
                Dim blockBlob As CloudBlockBlob = blobContainer.GetBlockBlobReference(p.ImageGuid)

                If blockBlob.Exists Then
                    Dim buffer(blockBlob.StreamWriteSizeInBytes - 1) As Byte
                    blockBlob.DownloadToByteArray(buffer, 0)

                    p.Image = buffer
                End If
            End If
        End Sub

        Private Sub ReadAnimalImageFromBlob(p As Animal)
            Try
                'Retrieve reference to the picture blob named after it's Guid.
                If p.ImageGuid IsNot Nothing Then
                    Dim blobContainer = GetBlobContainer()
                    Dim blockBlob As CloudBlockBlob = blobContainer.GetBlockBlobReference(p.ImageGuid)

                    If blockBlob.Exists Then
                        Dim buffer(blockBlob.StreamWriteSizeInBytes - 1) As Byte
                        blockBlob.DownloadToByteArray(buffer, 0)

                        p.Image = buffer
                        buffer = Nothing
                    End If
                End If
            Catch ex As Exception
                MsgBox(ex.Message.ToString)
            Finally

            End Try

        End Sub

        Private Sub Pictures_Deleting(entity As Picture)
            DeleteImageFromBlob(entity)
        End Sub

        Private Sub Animals_Deleting(entity As Animal)
            DeleteAnimalImageFromBlob(entity)
        End Sub
    End Class

End Namespace
